#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tkinter import *
import time
from re import sub
from urllib import parse
from tkinter import scrolledtext
import win32clipboard
import zhconv

LOG_LINE_NUM = 0




def hans_2_hant(hans_str: str):
    '''
    Function: 将 hans_str 由简体转化为繁体
    '''
    return zhconv.convert(hans_str, 'zh-hant')

def hant_2_hans(hant_str: str):
    '''
    Function: 将 hant_str 由繁体转化为简体
    '''
    return zhconv.convert(hant_str, 'zh-hans')

def strans(str_input):
    x = sub('\s+', '', str_input.decode("utf-8")).strip()
    str_output1 = x.encode("raw_unicode_escape").decode("unicode_escape")
    str_output2 = str_output1.encode("raw_unicode_escape").decode(
        "utf-8")
    return str_output2

def data_to_stamp(time_str_data):
    try:
        time_array = time.strptime(time_str_data, "%Y-%m-%d %H:%M:%S")
        time_stamp = str(int(time.mktime(time_array))*1000)
    except:
        time_stamp = "trans error"
    return time_stamp


def stamp_to_date(time_stamp):
    time_stamp = float(time_stamp) / 1000
    time_array = time.localtime(time_stamp)
    str_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
    return str_time

def time_trans(get_time):
    input_times = get_time.split("\n")
    res = ""
    for input_time in input_times:
        len_time = len(input_time)
        if len_time == 13:
            out_time = stamp_to_date(input_time)
        elif len_time == 10:
            out_time = stamp_to_date(input_time+"000")
        else:
            out_time = data_to_stamp(input_time)
        res = res + out_time + "\n"
    return res

class MY_GUI():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name


    #设置窗口
    def set_init_window(self):
        self.init_window_name.title("小工具v1.0")           #窗口名
        self.init_window_name.geometry('1068x681+10+10')
        #self.init_window_name["bg"] = "pink"                                    #窗口背景色，其他背景色见：blog.csdn.net/chl0000/article/details/7657887
        #self.init_window_name.attributes("-alpha",0.9)                          #虚化，值越小虚化程度越高
        #标签
        self.init_data_label = Label(self.init_window_name, text="待处理数据")
        self.init_data_label.grid(row=0, column=0)
        self.result_data_label = Label(self.init_window_name, text="输出结果")
        self.result_data_label.grid(row=0, column=12)
        self.log_label = Label(self.init_window_name, text="日志")
        self.log_label.grid(row=12, column=0)
        #文本框
        self.init_data_Text = Text(self.init_window_name, width=67, height=35)  #原始数据录入框
        self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10)
        self.result_data_Text = Text(self.init_window_name, width=70, height=49)  #处理结果展示
        self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
        self.log_data_Text = Text(self.init_window_name, width=66, height=9)  # 日志框
        self.log_data_Text.grid(row=13, column=0, columnspan=10)
        #按钮
        self.str_trans_to_md5_button = Button(self.init_window_name, text="hbase转换", bg="lightblue", width=10,command=self.str_trans_hbase)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=1, column=11)
        self.str_trans_to_md5_button = Button(self.init_window_name, text="url编码转换", bg="lightblue", width=10,command=self.str_trans_url)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=2, column=11)
        self.str_trans_to_md5_button = Button(self.init_window_name, text="时间转换", bg="lightblue", width=10,command=self.str_trans_time)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=3, column=11)
        self.str_trans_to_md5_button = Button(self.init_window_name, text="获取当前时间", bg="lightblue", width=10,command=self.str_get_time)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=4, column=11)
        self.str_trans_to_md5_button = Button(self.init_window_name, text="简体转繁体", bg="lightblue", width=10,command=self.hans2hant)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=5, column=11)
        self.str_trans_to_md5_button = Button(self.init_window_name, text="繁体转简体", bg="lightblue", width=10,command=self.hant2hans)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=6, column=11)
        self.str_trans_to_md5_button = Button(self.init_window_name, text="清空数据", bg="lightblue", width=10,command=self.clear_data)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=7, column=11)
        self.str_trans_to_md5_button = Button(self.init_window_name, text="复制结果", bg="lightblue", width=10,command=self.copyresultdata)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=8, column=11)
        self.str_trans_to_md5_button = Button(self.init_window_name, text="清空日志", bg="lightblue", width=10,command=self.clear_datalog)  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=12, column=1)


    #功能函数
    def str_trans_hbase(self):
        src = self.init_data_Text.get(1.0,END).strip().replace("\n","").encode()
        if src:
            try:
                resultData = strans(src)
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,resultData)
                self.write_log_to_Text("INFO: success")
            except:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,"字符串转失败")
        else:
            self.write_log_to_Text("ERROR: failed")
    
    def str_trans_url(self):
        src = self.init_data_Text.get(1.0,END).strip().replace("\n","").encode()
        if src:
            try:
                resultData = parse.unquote(strans(src))
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,resultData)
                self.write_log_to_Text("INFO: success")
            except:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,"字符串转失败")
        else:
            self.write_log_to_Text("ERROR: failed")

    def str_trans_time(self):
        src = self.init_data_Text.get(1.0,END).strip()
        if src:
            try:
                resultData = time_trans(src)
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,resultData)
                src_times = src.split("\n")
                out_times = resultData.split("\n")
                for i, src_time in enumerate(src_times):
                    self.write_log_to_Text("INFO: "+src_time+" To: "+out_times[i])
            except:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,"字符串转失败")
        else:
            self.write_log_to_Text("ERROR: failed") 
    
    def str_get_time(self):
        time_now = time.time()
        stamp_now = str(int(round(time_now*1000)))
        resultData = "时间戳为：     " + stamp_now + "\n时间格式显示： " + stamp_to_date(stamp_now)
        self.result_data_Text.delete(1.0,END)
        self.result_data_Text.insert(1.0,resultData)
    
    def hans2hant(self):
        src = self.init_data_Text.get(1.0,END).strip()
        if src:
            try:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,hans_2_hant(src))
            except:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,"字符串转失败")
        else:
            self.write_log_to_Text("ERROR: failed") 

    def hant2hans(self):
        src = self.init_data_Text.get(1.0,END).strip()
        if src:
            try:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,hant_2_hans(src))
            except:
                self.result_data_Text.delete(1.0,END)
                self.result_data_Text.insert(1.0,"字符串转失败")
        else:
            self.write_log_to_Text("ERROR: failed") 

    def clear_data(self):
        self.result_data_Text.delete(1.0,END)
        self.init_data_Text.delete(1.0,END)


    def clear_datalog(self):
        global LOG_LINE_NUM
        self.log_data_Text.delete(1.0,END)
        LOG_LINE_NUM = 0

    def copyresultdata(self):
        copystring = self.result_data_Text.get(1.0,END)[:-1]
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardText(copystring,win32clipboard.CF_TEXT)
        win32clipboard.CloseClipboard()
        self.write_log_to_Text("INFO: 复制结果到剪贴板")

    #获取当前时间
    def get_current_time(self):
        current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        return current_time

    #日志动态打印
    def write_log_to_Text(self,logmsg):
        global LOG_LINE_NUM
        current_time = self.get_current_time()
        logmsg_in = str(current_time) +" " + str(logmsg) + "\n"      #换行
        if LOG_LINE_NUM <= 7:
            self.log_data_Text.insert(END, logmsg_in)
            LOG_LINE_NUM = LOG_LINE_NUM + 1
        else:
            self.log_data_Text.delete(1.0,2.0)
            self.log_data_Text.insert(END, logmsg_in)


def gui_start():
    init_window = Tk()              #实例化出一个父窗口
    ZMJ_PORTAL = MY_GUI(init_window)
    # 设置根窗口默认属性
    ZMJ_PORTAL.set_init_window()

    init_window.mainloop()          #父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示


gui_start()